//
//  CheckboxButton.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/15.
//

import UIKit

class CheckboxButton: BaseButton {
    var clickClosure: ((Int)->Void)?
    
    let btnTitleLabel = BaseLabel()
    let btnImageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpView() {
        self.backgroundColor = .clear
        //image
        btnImageView.image = R.image.login_savepwd_off()
        btnImageView.contentMode = .center
        self.addSubview(self.btnImageView)
        btnImageView.snp.remakeConstraints { make in
            make.left.centerY.equalToSuperview()
            make.height.width.equalTo(24)
        }
        //title
        btnTitleLabel.setFont(R.font.interMedium(size: 14))
        btnTitleLabel.textColor = UIColor(hexStr: "#292D32")
        btnTitleLabel.textAlignment = .left
        btnTitleLabel.numberOfLines = 0
        self.addSubview(self.btnTitleLabel)
        btnTitleLabel.snp.remakeConstraints { make in
            make.left.equalTo(btnImageView.snp.right).offset(5)
            make.top.equalToSuperview()
            make.height.greaterThanOrEqualTo(btnImageView)
            make.right.bottom.equalToSuperview()
        }
        self.addTarget(self, action: #selector(click), for: UIControl.Event.touchUpInside)
    }
    convenience init(title: String, hexstr: String = "#292D32", checkFlag: Bool = false){
        self.init(frame: CGRect.zero)
        self.btnTitleLabel.textColor = UIColor(hexStr: hexstr)
        self.btnTitleLabel.text = title
        if checkFlag {//默认选中
            self.check()
        }
    }
    
    @objc func click(){
        if self.tag == 0 {
            self.check()
        }else{
            self.unCheck()
        }
    }
    //勾选上
    func check(){
        self.tag = 1
        self.btnImageView.image = R.image.login_savepwd_on()
        self.clickClosure?(self.tag)
    }
    //取消勾选
    func unCheck(){
        self.tag = 0
        self.btnImageView.image = R.image.login_savepwd_off()
        self.clickClosure?(self.tag)
    }
}
